package common.classes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

import main.classes.Server;

public class FileResponseThread implements Runnable {
	Socket socket;
	String fullFilePath;
	HeaderWorker parser;
	File file;
	
	public FileResponseThread(Socket socket, String fullFilePath, HeaderWorker parser) {
		this.socket = socket;
		this.fullFilePath = new String(fullFilePath);
		this.parser = parser;
		this.file = new File(fullFilePath);
	}
	
	public void run() {
		try {
			FileInputStream is = new FileInputStream(file);
			OutputStream os = socket.getOutputStream();
			os.write("HTTP\\1.1 200 Or\r\n".getBytes());
			
			if (parser.isWillCreateCookie()) {
				SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
				os.write(("Set-cookie: sid=" + parser.getcSID() + 
						", Expires=" + sdf.format(new Date(parser.getcTime())) + "\r\n").getBytes());
				os.write(("Set-cookie: stime=" + parser.getcTime() + 
						", Expires=" + sdf.format(new Date(parser.getcTime())) + "\r\n").getBytes());
			}
			
			os.write(("Content-type: " + FileNameWorker.contentTypeOf(fullFilePath) + "\r\n").getBytes());
			os.write("\r\n".getBytes());
			int len = is.available();
			byte []bytes = new byte[len];
			is.read(bytes);
			os.write(bytes);
			os.flush();
			is.close();
		} catch (FileNotFoundException e) {
			System.err.println(e);
		} catch (IOException e) {
			System.err.println(e);
		} finally {
			Server.getLoger().log(parser.getcSID(), parser.getFilePath(), true);
			try {
				socket.close();
			} catch (IOException e) {
				System.err.println(e);
			}
		}	
	}
}